package fei.zhou.jwtlearn;

import static io.jsonwebtoken.SignatureAlgorithm.HS256;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;

@SpringBootTest
class JWTTest2 {
    
    @Test
    void t1() {
        Map<String, Object> map = new HashMap<>();
        
        String token = JWT.create().withHeader(map) // header
                .withClaim("userId", 21)// payload
                .withClaim("username", "小明")// payload
                // .withExpiresAt(new Date())//指定令牌的过期时间
                .sign(Algorithm.HMAC256("zhoufei")) // 签名
        ;
        System.out.println("生成token---->>" + token);
        // 生成token---->>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjIxLCJ1c2VybmFtZSI6IuWwj-aYjiJ9.VQv-vsTkrrM1xLORTGYQdmKMAJJjZLn37s5ridn2wso
        
    }
    
    // 令牌验证:根据令牌和签名解析数据
    // 常见异常：
    // SignatureVerificationException 签名不一致异常
    // TokenExpiredException 令牌过期异常
    // AlgorithmMismatchException 算法不匹配异常
    // InvalidClaimException 失效的payload异常
    @Test
    void t2() {
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzb3VyY2VJZHMiXSwidXNlcl9uYW1lIjoiemhhbmdzYW4iLCJzY29wZSI6WyJhbGwiXSwiZXhwIjoxNjA4NjczOTMzLCJhdXRob3JpdGllcyI6WyJ1c2VyLXJvbGUiXSwianRpIjoiZWM0YzJjNTYtZDA0Mi00OGM3LTg2MWEtYTRkMGFlNmI4MTUyIiwiY2xpZW50X2lkIjoiY2xpZW50SWQifQ.hNGAaltB3m4EgPS_O44pTeW3Pn9y-zZKu-aIzlKJWB4";
        
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("SIGNING_KEY")).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        System.out.println("解析token---->>" + claims);


        System.out.println("用户Id：" + decodedJWT.getClaim("userId").asInt());
        System.out.println("用户名：" + decodedJWT.getClaim("username"));
        System.out.println("过期时间：" + decodedJWT.getExpiresAt());

        DecodedJWT decodedJWT2 = JWT.require(Algorithm.HMAC256("SIGNING_KEY")).build().verify(token);
        Map<String, Claim> claims2 = decodedJWT2.getClaims();
        System.out.println("解析token---->>" + claims2);
        // 用户Id：21
        // 用户名：com.auth0.jwt.impl.JsonNodeClaim@77b9d0c7
        // 过期时间：null
        
    }
    
}
